#      t.string :name

class LoggedController < ActiveRecord::Base
	validates_presence_of :name
	
	has_many :logged_actions
	
	class << self
		def find_or_create_by_name(name)
			lc = find_by_name name
			lc || create( :name => name )
		end
	end
	
	def logged_actions_sorted_by(sorter, dir)
		actions = case sorter
			when "name" 	: logged_actions.sort_by { |lc| lc.name }
			when "count"	: logged_actions.sort { |lca, lcb| lcb.count <=> lca.count }
			when "completion_time" : logged_actions.sort { |lca, lcb| lcb.average_completion_time <=> lca.average_completion_time }
			when "render_time" : logged_actions.sort { |lca, lcb| lcb.average_render_time <=> lca.average_render_time }
			when "db_time" : logged_actions.sort { |lca, lcb| lcb.average_db_time <=> lca.average_db_time }
			else logged_actions
		end
    actions.reverse! unless dir == "normal"
    actions
	end
	
	# convert "SomeThingController" into "Some Thing"
	def title_name
		title = name[-10..-1] == "Controller" ? name[0..-11] : name
		title.gsub(/([A-Z]+)([A-Z][a-z])/,'\1 \2').
			gsub(/([a-z\d])([A-Z])/,'\1 \2')
	end
	
  def count=(cnt)
    @count = cnt
  end
  
	def count
		@count || LogEntry.count_by_logged_controller_id(self.id)
	end
	
  def max_completion_time
		@max_completion_time ||= (LogEntry.times_for_controller_id(self.id)[:max_completion] || 0.0)
	end
  
  def min_completion_time
		@min_completion_time ||= (LogEntry.times_for_controller_id(self.id)[:min_completion] || 0.0)
	end
  
	# average time to complete this controller in seconds
	def average_completion_time
		@average_completion_time ||= (LogEntry.times_for_controller_id(self.id)[:avg_completion] || 0.0)
	end
	
	# average time to render this controller in seconds
	def average_render_time
		@average_render_time ||= (LogEntry.times_for_controller_id(self.id)[:render] || 0.0)
	end
	
	# average db time for this controller in seconds
	def average_db_time
		@average_db_time ||= (LogEntry.times_for_controller_id(self.id)[:db] || 0.0)
	end
	
  def max_completion_time_in_ms
		(max_completion_time * 1000).to_i
	end
  
  def min_completion_time_in_ms
		(min_completion_time * 1000).to_i
	end
  
	# average time to complete this controller in milliseconds
	def average_completion_time_in_ms
		(average_completion_time * 1000).to_i
	end
	
	# average time to render this controller in milliseconds
	def average_render_time_in_ms
		(average_render_time * 1000).to_i
	end
	
	# average db time for this controller in milliseconds
	def average_db_time_in_ms
		(average_db_time * 1000).to_i
	end
end
